package com.example.manage_dzensaas.service;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.example.manage_dzensaas.core.utils.DateUtils;
import com.example.manage_dzensaas.core.utils.StringUtils;
import com.example.manage_dzensaas.filter.exception.CustomException;
import com.example.manage_dzensaas.listener.ProductInfoExcelListener;
import com.example.manage_dzensaas.mapper.db1.ProductInfoMapper;
import com.example.manage_dzensaas.pojo.bo.AllProductsBo;
import com.example.manage_dzensaas.pojo.bo.ProductInfoBo;
import com.example.manage_dzensaas.pojo.dto.ProductInfoExcelDTO;
import com.example.manage_dzensaas.pojo.entity.db1.ProductInfo;
import com.example.manage_dzensaas.pojo.result.ApiResult;
import com.opencsv.CSVReader;
import org.apache.ibatis.solon.annotation.Db;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.UploadedFile;
import org.noear.solon.data.annotation.Tran;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Component
public class ProductInfoService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ProductInfoService.class);

    @Db
    ProductInfoMapper productInfoMapper;

    public List<ProductInfo> findAll(AllProductsBo allProductsBo) {
        return new QueryChainWrapper<>(productInfoMapper)
                .apply(StringUtils.isNotBlank(allProductsBo.getSku()), "sku = {0}", allProductsBo.getSku())
                .apply(StringUtils.isNotBlank(allProductsBo.getAddedBy()), "added_by like concat('%', {0}, '%')", allProductsBo.getAddedBy())
                .apply(StringUtils.isNotBlank(allProductsBo.getStoreName()), "store_name = {0}", allProductsBo.getStoreName())
                .apply(StringUtils.isNotBlank(allProductsBo.getProductName()), "product_name like concat('%', {0}, '%')", allProductsBo.getProductName())
                .apply(StringUtils.isNotBlank(allProductsBo.getTagInfo()), "tag_info = {0}", allProductsBo.getTagInfo())
                .orderByDesc("added_time")
                .last("limit 10")
                .list();
    }


    public int batchInsertOrUpdate(ArrayList<ProductInfo> batchList) {
        return productInfoMapper.batchInsertOrUpdate(batchList);
    }

    public void importFromExcel(UploadedFile file, String addedBy) {
        LOGGER.info("开始解析excel文件");
        try {
            InputStream inputStream = file.getContent();
            EasyExcel.read(inputStream, ProductInfoExcelDTO.class, new ProductInfoExcelListener(this, addedBy))
                    .sheet()
                    .doRead();
        } catch (Exception e) {
            LOGGER.error("excel文件解析失败", e);
            throw new RuntimeException(e);
        } finally {
            try {
                file.delete();
            } catch (IOException e) {
                LOGGER.error("文件删除失败", e);
            }
        }
    }

    @Tran
    public ApiResult addProductInfo(ProductInfoBo productInfoBo) {
        if (StringUtils.isBlank(productInfoBo.getAddedBy())) {
            return ApiResult.error("添加失败，操作人不能为空");
        }
        if (productInfoBo.getAddedBy().length() > 6) {
            return ApiResult.error("操作人不能大于6位数");
        }
        if (Objects.isNull(productInfoBo.getAddedTime())) {
            return ApiResult.error("添加失败，添加时间不能为空");
        }
        if (productInfoBo.getProductInfoListBo() == null && productInfoBo.getProductInfoListBo().size() == 0) {
            return ApiResult.error("添加失败，添加数据不能为空");
        }
        if (productInfoBo.getProductInfoListBo().size() > 10) {
            return ApiResult.error("添加失败，添加数据集一次请求不能大于10条");
        }
        ArrayList<ProductInfo> batchList = new ArrayList<>();
        for (ProductInfoBo.ProductInfoRequest productInfo : productInfoBo.getProductInfoListBo()) {
            boolean b = productInfo.getSku() != null && !productInfo.getSku().isEmpty()
                    && productInfo.getProductName() != null && !productInfo.getProductName().isEmpty()
                    && productInfo.getFinalPrice() != null && productInfo.getOriginalPrice() != null;
            if (!b) {
                return ApiResult.error("添加失败，SKU: " + productInfo.getSku() + " 有为空字段");
            }
            ProductInfo product = new ProductInfo();
            product.setSku(productInfo.getSku());
            product.setProductName(productInfo.getProductName());
            product.setFinalPrice(productInfo.getFinalPrice());
            product.setOriginalPrice(productInfo.getOriginalPrice());
            product.setSubsidyPrice(productInfo.getSubsidyPrice());
            product.setStoreName(productInfo.getStoreName());
            product.setCommentCount(productInfo.getCommentCount());
            product.setTagInfo(productInfo.getTagInfo());
            product.setImageUrl(productInfo.getImageUrl());
            product.setAddedBy(productInfoBo.getAddedBy());
            product.setAddedTime(DateUtils.convertMillisToDate(productInfoBo.getAddedTime()));
            batchList.add(product);
        }
        int i = productInfoMapper.batchInsertOrUpdate(batchList);
        return i >= 1 ? ApiResult.success("添加成功") : ApiResult.error("更新添加失败");
    }

    @Tran
    public void importFromCSV(UploadedFile file, String addedBy) {
        LOGGER.info("开始解析CSV文件");
        // 检查文件是否为空
        if (file == null || file.getContent() == null) {
            throw new CustomException("file 文件为空");
        }
        // 使用 file.getContent() 获取 InputStream
        InputStream inputStream = file.getContent();

        // 解析 CSV 文件
        ArrayList<ProductInfo> cachedDataList = new ArrayList<>();
        try (CSVReader reader = new CSVReader(new InputStreamReader(inputStream))) {
            String[] nextLine;
            // 跳过 CSV 文件的标题行（如果有）
            reader.readNext();
            // 逐行读取 CSV 文件
            while ((nextLine = reader.readNext()) != null) {
                // 假设 CSV 文件的列顺序
                // 创建 ProductInfo 对象并添加到列表
                ProductInfo productInfo = new ProductInfo();
                // 转换并设置字段
                if (nextLine != null && nextLine.length >= 1 && StringUtils.isNotBlank(nextLine[0])) {
                    productInfo.setSku(nextLine[0]);
                } else {
                    throw new CustomException("SKU不能为空");
                }
                if (nextLine != null && nextLine.length >= 2 && StringUtils.isNotBlank(nextLine[1])) {
                    productInfo.setProductName(nextLine[1]);
                } else {
                    productInfo.setProductName(null);
                }
                if (nextLine != null && nextLine.length >= 3 && StringUtils.isNotBlank(nextLine[2])) {
                    productInfo.setFinalPrice(new BigDecimal(nextLine[2]));
                } else {
                    productInfo.setFinalPrice(null);
                }
                if (nextLine != null && nextLine.length >= 4 && StringUtils.isNotBlank(nextLine[3])) {
                    productInfo.setOriginalPrice(new BigDecimal(nextLine[3]));
                } else {
                    productInfo.setOriginalPrice(null);
                }
                if (nextLine != null && nextLine.length >= 5 && StringUtils.isNotBlank(nextLine[4])) {
                    productInfo.setSubsidyPrice(new BigDecimal(nextLine[4]));
                } else {
                    productInfo.setSubsidyPrice(null);
                }
                if (nextLine != null && nextLine.length >= 6 && StringUtils.isNotBlank(nextLine[5])) {
                    productInfo.setStoreName(nextLine[5]);
                } else {
                    productInfo.setStoreName(null);
                }
                if (nextLine != null && nextLine.length >= 7 && StringUtils.isNotBlank(nextLine[6])) {
                    productInfo.setCommentCount(nextLine[6]);
                } else {
                    productInfo.setCommentCount(null);
                }
                if (nextLine != null && nextLine.length >= 8 && StringUtils.isNotBlank(nextLine[7])) {
                    productInfo.setTagInfo(nextLine[7]);
                } else {
                    productInfo.setTagInfo(null);
                }
                if (nextLine != null && nextLine.length >= 9 && StringUtils.isNotBlank(nextLine[8])) {
                    productInfo.setImageUrl(nextLine[8]);
                } else {
                    productInfo.setImageUrl(null);
                }
                // 设置默认值
                productInfo.setAddedTime(new Date());
                productInfo.setCreatedTime(new Date());
                productInfo.setUpdatedTime(new Date());
                productInfo.setAddedBy(addedBy);
                cachedDataList.add(productInfo);
            }
            // 新增成功
            productInfoMapper.batchInsertOrUpdate(cachedDataList);
        } catch (Exception e) {
            LOGGER.error("CSV文件解析失败", e);
            throw new RuntimeException(e);
        }
    }
}
